package com.situ.admin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.situ.admin.interceptor.RootInterceptor;

/**
 * 
 * @author: JavaSiegeLoin(Gang)
 * @E-mail: wzg15653@163.com
 * @创建日期: 2021年10月14日 下午3:28:25
 * @ClassName: WebConfig
 * @类描述-Description:配置文件
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

	@Autowired
	private RootInterceptor rootInterceptor;

	// 从配置文件中读取一个值
	@Value("${spring.servlet.multipart.location}")
	private String path;

	// 静态资源的映射
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/upload/**").addResourceLocations("file:" + path);
	}

	// 配置拦截器
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(rootInterceptor).addPathPatterns("/**").excludePathPatterns("/api/roots", "/vercode/**",
				"/vercode", "/upload/**");
	}

	@Bean
	public CorsFilter corsFilter() {
		CorsConfiguration config = new CorsConfiguration();
		config.addAllowedOrigin("*"); // 允许的域
		// config.setAllowCredentials(true);
		config.addAllowedMethod("*");
		config.addAllowedHeader("*");
		config.addExposedHeader("token");// 允许浏览器读取token的值
		UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
		configSource.registerCorsConfiguration("/**", config);
		return new CorsFilter(configSource);
	}
}
